﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Text;
using Common;

namespace Habito.Admini
{
	public partial class SolutionEdit : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

			if (string.IsNullOrEmpty(Ticket.UserName) || Session["username"] == null)
			{
				Response.Redirect("Login.aspx");
			}
			if (!string.IsNullOrEmpty(Request.QueryString["classID"]))
			{
				ViewState["classID"] = Request.QueryString["classID"].Replace("\'", "");
			}

			if (!string.IsNullOrEmpty(Request.QueryString["id"]))
			{
				ViewState["id"] = Request.QueryString["id"].Replace("\'", "");
			}
			Ajax.BLL.SolutionClass solution = new Ajax.BLL.SolutionClass();
			var list = solution.GetModelList("");
			StringBuilder temp = new StringBuilder();
			foreach (var item in list)
			{
				temp.AppendFormat("<option value = '{0}'>{1}</option>", item.ID, item.ClassName);
			}
			ViewState["options"] = temp.ToString();
		}

		protected override void OnInit(EventArgs e)
		{
			if (Request.QueryString["GetSolutionByID"] == "1")
			{
				int id = int.Parse(Request.QueryString["id"].Replace("\'", ""));
				Ajax.BLL.Solutions slu = new Ajax.BLL.Solutions();
				Response.Write(JsonConvert.SerializeObject(slu.GetModel(id)));
				Response.End();
			}
			else if (Request.QueryString["SaveSolution"] == "1")
			{
				int id = int.Parse(Request.QueryString["id"].Replace("\'", ""));
				string title = Request.Params["title"];
				int showIndex = int.Parse(Request.Params["showIndex"].Replace("\'", ""));
				int showInClass = int.Parse(Request.Params["showInClass"].Replace("\'", ""));
				Ajax.Model.Solutions cla = new Ajax.Model.Solutions();
				cla.ID = id;
				cla.Title = title;
				cla.Description = Request.Params["description"];
				cla.ClassID = int.Parse(Request.Params["classID"].Replace("\'", ""));
				cla.UpdateTime = DateTime.Now;
				cla.ShowInClass = showInClass;
				cla.ShowInIndex = showIndex;
				Ajax.BLL.Solutions cll = new Ajax.BLL.Solutions();

				if (id == 0)
				{
					Response.Write(JsonConvert.SerializeObject(cll.Add(cla)));
					Response.End();
				}
				else
				{
					cla.ID = id;
					Response.Write(JsonConvert.SerializeObject(cll.Update(cla)));
					Response.End();
				}
			}
			base.OnInit(e);
		}
	}
}